import { StrictMode } from "react";
import { createRoot, Root } from "react-dom/client";
import App from "./App.tsx";

let root: Root | null = null;

// 独立运行
function render(props?: any) {
  const container = props?.container ? props.container.querySelector("#root") : document.getElementById("root");

  console.log("已在子应用中接受到来自主应用的props===哈哈哈", props);
  if (!container) {
    throw new Error("Root element not found");
  }

  root = createRoot(container);
  root.render(
    <StrictMode>
      <App />
    </StrictMode>
  );
}

// 独立运行时直接渲染
// 判断是否在 qiankun 环境中
if (!(window as any).__POWERED_BY_QIANKUN__) {
  render();
}

// 声明全局类型
declare global {
  interface Window {
    __POWERED_BY_QIANKUN__?: boolean;
    __INJECTED_PUBLIC_PATH_BY_QIANKUN__?: string;
  }
}

// qiankun 生命周期函数
export async function bootstrap() {
  console.log("[qiankun] 子应用 bootstrap");
}

export async function mount(props: any) {
  console.log("[qiankun] 子应用 mount", props);
  render(props);
}

export async function unmount(props: any) {
  console.log("[qiankun] 子应用 unmount", props);
  if (root) {
    root.unmount();
    root = null;
  }
}

// 将生命周期函数挂载到 window 对象上，确保 qiankun 能够找到
// 这是为了兼容 qiankun 的加载机制
// 注意：这里的 key 需要与主应用配置中的 name 一致（通常是 'guide-app'）
if (typeof window !== "undefined") {
  // 支持多个可能的名称，确保兼容性
  const appNames = ["guide-app", "my-react-ts-app"];
  const lifecycle = {
    bootstrap,
    mount,
    unmount,
  };

  appNames.forEach((name) => {
    (window as any)[name] = lifecycle;
  });
}
